﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Nancy.Helpers;
using QQ2564874169.Core;
using QQ2564874169.Core.Encryption;
using QQ2564874169.Core.Utils;

namespace 新商盟
{
    class Program
    {
        private const string dir = "sessionid";
        private static Dictionary<string, string> _cache = new Dictionary<string, string>();

        private static string EncryptPwd(string pwd)
        {
            var sign = "{1#2$3%4(5)6@7!poeeww$3%4(5)djjkkldss}";
            return Encrypt.MD5(Encrypt.MD5(pwd + sign) + sign);
        }

        private static string GetCookie(string setcookie, string name)
        {
            var index = setcookie.LastIndexOf(name, StringComparison.OrdinalIgnoreCase);
            if (index < 0)
                return "";
            index = setcookie.IndexOf("=", index, StringComparison.Ordinal);
            var end = setcookie.IndexOf(";", index, StringComparison.Ordinal);
            return setcookie.Substring(index + 1, end - index - 1);
        }

        private static void SaveSessionID(string name, string sessionid)
        {
            if (Directory.Exists(dir) == false)
            {
                Directory.CreateDirectory(dir);
            }
            var filename = Path.Combine(dir, name + ".txt");

            using (var file = File.Open(filename, FileMode.Create))
            {
                var data = Encoding.UTF8.GetBytes(sessionid);
                file.Write(data, 0, data.Length);
            }
        }

        private static string GetSessionID(string loginName, string loginPwd, bool clear = false)
        {
            var filename = Path.Combine(dir, loginName + ".txt");
            if (_cache.ContainsKey(loginName) == false && clear == false)
            {
                if (File.Exists(filename))
                {
                    _cache.Add(loginName, File.ReadAllText(filename, Encoding.UTF8));
                }
            }
            if (_cache.ContainsKey(loginName) == false || clear)
            {
                var map = new Dictionary<string, string>
                {
                    {"jsonp", "jQuery172014655291264453485_1517823029356"},
                    {"protocol", "http"},
                    {"loginIndex", "http://www.xinshangmeng.com/xsm2/"},
                    {"j_username", loginName},
                    {"j_mcmm", EncryptPwd(loginPwd)},
                    {"j_valcode", ""},
                    {"_", DateTime.Now.ToLongTime().ToString()}
                };
                var param = string.Join("&", map.Keys.Select(k => k + "=" + HttpUtility.UrlEncode(map[k])));
                var url = "http://login.xinshangmeng.com/login/users/dologin/up?" + param;
                var resp = HttpHelper.Get(url) as HttpWebResponse;
                var setcookie = resp.Headers["set-cookie"];
                var cookies = new[]
                {
                    "xsm_client", "uniqueuserid", "gray_scale", "st_uid", "operatTime", "xsmDomain",
                    "protocol", "xsm_file_version", "st_userproperty", "xsmversion", "domainurl", "xsmlog",
                    "index_userid"
                }.Select(i => new Cookie(i, GetCookie(setcookie, i), "/", "xinshangmeng.com"));

                var req = HttpHelper.Request(
                    "http://jx.xinshangmeng.com:82/eciop/order/cgtco.do?method=checkCo&callback=jQuery_1517911474091&_=" +
                    DateTime.Now.ToLongTime(), "GET");
                req.CookieContainer = new CookieContainer();
                foreach (var c in cookies)
                {
                    req.CookieContainer.Add(c);
                }
                resp = req.GetResponse() as HttpWebResponse;
                if (resp.StatusCode != HttpStatusCode.OK)
                    throw new Exception("登录失败。");
                setcookie = resp.Headers["set-cookie"];
                var sid = GetCookie(setcookie, "JSESSIONID");
                if (_cache.ContainsKey(loginName))
                    _cache.Remove(loginName);
                _cache.Add(loginName, sid);
                SaveSessionID(loginName, _cache[loginName]);
            }
            return _cache[loginName];
        }

        private static bool TestSession(string sessionid)
        {
            var req = HttpHelper.Request("http://jx.xinshangmeng.com:82/eciop/orderForCC/cgtListForCC.htm", "GET");
            req.CookieContainer = new CookieContainer();
            req.CookieContainer.Add(new Cookie("JSESSIONID", sessionid, "/", "xinshangmeng.com"));
            try
            {
                var resp = req.GetResponse() as HttpWebResponse;
                if (resp.StatusCode != HttpStatusCode.OK)
                    return false;
                return resp.ContentType.ToLower().Contains("xml") == false;
            }
            catch
            {
                return false;
            }
        }

        static void Main(string[] args)
        {
            var sid = GetSessionID("361002104846", "792214");

            if (TestSession(sid) == false)
            {
                sid = GetSessionID("361002104846", "792214", true);
                Console.WriteLine("updated");
            }

            var req = HttpHelper.Request("http://jx.xinshangmeng.com:82/eciop/orderForCC/cgtListForCC.htm", "GET");
            req.CookieContainer = new CookieContainer();
            req.CookieContainer.Add(new Cookie("JSESSIONID", sid, "/", "xinshangmeng.com"));
            var resp = req.GetResponse();

            var html = resp.Read(Encoding.GetEncoding("GBK"));
            Console.WriteLine(html);

            Console.Read();
        }
    }
}
